// 注意：这是一个vuex@3 的 module 对象，只能应用在Vue2项目中
import {
  getCategory1List,
  getCategory2List,
  getCategory3List,
} from "@/api/product";

const state = {
  category1Id: undefined,
  category2Id: undefined,
  category3Id: undefined,
  category1List: [],
  category2List: [],
  category3List: [],
};
const mutations = {
  UPDATE_CATEGORY1LIST(state, category1List) {
    state.category1List = category1List;
  },
  UPDATE_CATEGORY2LIST(state, { category2List, category1Id }) {
    state.category2List = category2List;
    state.category1Id = category1Id;
  },
  UPDATE_CATEGORY3LIST(state, { category3List, category2Id }) {
    state.category3List = category3List;
    state.category2Id = category2Id;
  },
  UPDATE_CATEGORY3ID(state, newVal) {
    state.category3Id = newVal;
  },
  RESET_CATEGORY2LIST(state) {
    state.category2List = [];
    state.category2Id = undefined;
  },
  RESET_CATEGORY3LIST(state) {
    state.category3List = [];
    state.category3Id = undefined;
  },
  RESET_STATE(state) {
    state.category1Id = undefined;
    state.category2Id = undefined;
    state.category3Id = undefined;
    state.category2List = [];
    state.category3List = [];
    state.category1List = [];
  },
};
const actions = {
  async getCategory1List({ commit }) {
    const res = await getCategory1List();
    commit("UPDATE_CATEGORY1LIST", res.data);
  },
  async getCategory2List({ commit }, category1Id) {
    const res = await getCategory2List(category1Id);
    commit("UPDATE_CATEGORY2LIST", { category2List: res.data, category1Id });
  },
  async getCategory3List({ commit }, category2Id) {
    const res = await getCategory3List(category2Id);
    commit("UPDATE_CATEGORY3LIST", { category3List: res.data, category2Id });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
